/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.sms.web;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.utils.StringUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.CustomerEmployeeRelationship;
import com.chlitina.store.modules.base.entity.CustomerGroup;
import com.chlitina.store.modules.base.entity.CustomerGroupDetail;
import com.chlitina.store.modules.base.service.CustomerEmployeeRelationshipService;
import com.chlitina.store.modules.base.service.CustomerGroupService;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.sms.entity.SmsStoreGroupToCustomer;
import com.chlitina.store.modules.sms.quartz.StoreGroupToCustomerQueueGenerate;
import com.chlitina.store.modules.sms.utils.SmsUtils;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.service.SystemService;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 店面群发给客户Controller
 * @author lvbo
 * @version 2013-06-25
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/sms/sendStoreGroupToCustomer")
public class SendStoreGroupToCustomerController extends BaseController {
	
	@Autowired
	private StoreGroupToCustomerQueueGenerate storeGroupToCustomerQueueGenerate;
	
	@Autowired
	private CustomerGroupService customerGroupService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private CustomerEmployeeRelationshipService customerEmployeeRelationshipService;
	
	@RequestMapping(value = "form")
	public String form(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		List<Customer> customers = StoreUtils.getStoreCustomers();
		model.addAttribute("customers", customers);
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendStoreGroupToCustomerForm";
	}
	
	@RequestMapping(value = "all")
	public String all(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		model.addAttribute("target", "all");
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendStoreGroupToAllCustomerForm";
	}
	
	@RequestMapping(value = "group")
	public String group(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		
		List<CustomerGroup> customerGroupList = customerGroupService.getByStore(StoreUtils.getStore().getId());
		model.addAttribute("target", "group");
		model.addAttribute("customerGroupList", customerGroupList);
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendStoreGroupToGroupCustomerForm";
	}
	
	@RequestMapping(value = "select")
	public String select(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		List<Customer> customers = StoreUtils.getStoreCustomers();
		model.addAttribute("customers", customers);
		model.addAttribute("target", "select");
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendStoreGroupToCustomerForm";
	}
	
	@RequestMapping(value = "customerList")
	public String customerList(@RequestParam("customerIds") String customerIds, HttpServletRequest request, SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		List<Customer> customerList = Lists.newArrayList();
		if (!StringUtils.isEmpty(customerIds)) {
			String[] cids = customerIds.split(",");
			for (String cid : cids) {
				Customer customer = customerService.get(Long.parseLong(cid));
				customerList.add(customer);
			}
		}
		String target = request.getParameter("target");
		model.addAttribute("target", target);
		model.addAttribute("customerList", customerList);
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendGroupToSelectCustomerForm";
	}
	
	@RequestMapping(value = "nonworkEmployeeForm")
	public String nonworkEmployeeForm(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		Store store = StoreUtils.getStore();
		List<Employee> employeeList = employeeService.findByStore(store, Employee.STATUS_NONWORKING);
		List<CustomerEmployeeRelationship> cerList = Lists.newArrayList();
		for (Employee e : employeeList) {
			List<CustomerEmployeeRelationship> cer = customerEmployeeRelationshipService.findByEmployee(e.getId());
			cerList.addAll(cer);
		}
		model.addAttribute("target", "nonworkEmployeeForm");
		model.addAttribute("employeeList", employeeList);
		model.addAttribute("cerList", cerList);
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendNonworkEmployeeGroupToCustomerForm";
	}
	
	@RequestMapping(value = "workEmployeeForm")
	public String workEmployeeForm(SmsStoreGroupToCustomer storeGroupToCustomer, Model model) {
		storeGroupToCustomer = new SmsStoreGroupToCustomer();
		Store store = StoreUtils.getStore();
		List<Employee> employeeList = employeeService.findByStore(store, Employee.STATUS_WORKING);
		model.addAttribute("target", "workEmployeeForm");
		model.addAttribute("employeeList", employeeList);
		model.addAttribute("storeGroupToCustomer", storeGroupToCustomer);
		return "modules/sms/sendWorkEmployeeGroupToCustomerForm";
	}

	@RequestMapping(value = "saveGroup")
	public String saveGroup(SmsStoreGroupToCustomer storeGroupToCustomer, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		String[] customerGroupIds = request.getParameterValues("customerGroupIds");
		String immediateSend = request.getParameter("sendType");
		boolean isSend = immediateSend != null && immediateSend.equals("true");
		Calendar calendar = SmsUtils.getPlanSendTime(isSend);
		storeGroupToCustomerQueueGenerate.setPlanSendTime(calendar);
		Store store = StoreUtils.getStore(true);
		int remainSmsAmount = store.getSms_remain_amount();
		Set<Long> customerIds = Sets.newHashSet();
		if (customerGroupIds != null) {
			for (String cgId : customerGroupIds) {
				CustomerGroup customerGroup = customerGroupService.get(Long.parseLong(cgId));
				List<CustomerGroupDetail> customerGroupDetailList = customerGroup.getCustomerGroupDetailList();
				for (CustomerGroupDetail cgd : customerGroupDetailList) {
					customerIds.add(cgd.getCustomer().getId());
				}
			}
		}
		boolean flag = false;
		boolean systemFlag = false;
		int index = 0; 
		Iterator<Long> iterator = customerIds.iterator();
		//获取短信内容
		String msg = storeGroupToCustomer.getMsgContent();
		while (iterator.hasNext()) {
			if (!flag || !systemFlag) {
				//验证短信剩余条数是否足够
				systemFlag = storeGroupToCustomerQueueGenerate.volidate();
				int smsNum = storeGroupToCustomerQueueGenerate.getSmsNum(msg.length());
				if (remainSmsAmount < smsNum) {
					flag = true;
					break;
				}
				remainSmsAmount -= smsNum;
				Long cid = iterator.next();
				//获取客户
				Customer customer = customerService.get(cid);
				storeGroupToCustomerQueueGenerate.load(store, customer.getMobile(), customer, msg);
				storeGroupToCustomerQueueGenerate.generate();
				smsNum = storeGroupToCustomerQueueGenerate.getSmsNum(msg.length());
				index = index + smsNum;
			}
		}
		store.setSms_remain_amount(store.getSms_remain_amount() - index);
		systemService.save(store);
		if (customerIds == null || customerIds.size() == 0) {
			addMessage(redirectAttributes, "所选择的客户群没有客户");
		}
		if (systemFlag) {
			addMessage(redirectAttributes, "系统剩余短信不足！无法发送短信");
		} else if (flag) {
			if (index == 0) {
				addMessage(redirectAttributes, "剩余短信不足！无法发送短信");
			} else {
				if (isSend) {
					addMessage(redirectAttributes, "由于剩余短信不足, " + index + "条短信发送成功！");
				} else {
					addMessage(redirectAttributes, "剩余短信不足，可成功保存" + index + "条短信，将于预定时间的发送。。。");
				}
			}
		} else {
			if (index != 0) {
				if (isSend) {
					addMessage(redirectAttributes, "" + index + "条短信发送成功！");
				} else{
					addMessage(redirectAttributes, "保存" + index + "条短信成功，将于预定时间开始发送。。。");
				}
			}
		}
		return "redirect:"+Global.ADMIN_PATH+"/sms/sendStoreGroupToCustomer/group";
	}
	@RequestMapping(value = "save")
	public String save(SmsStoreGroupToCustomer storeGroupToCustomer, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		String[] ids = request.getParameterValues("customerIds");
		String immediateSend = request.getParameter("sendType");
		String isEmployee = request.getParameter("isEmployee");
		String del = request.getParameter("delRealtionship");
		if ("true".equals(del)) {
			//解除离职员工和客户的关系
			String employeeId = request.getParameter("employeeIds");
			try {
				customerEmployeeRelationshipService.delete(null, Long.parseLong(employeeId));
			} catch (Exception e) {
			}
		}
		boolean isSend = immediateSend != null && immediateSend.equals("true");
		Calendar calendar = SmsUtils.getPlanSendTime(isSend);
		storeGroupToCustomerQueueGenerate.setPlanSendTime(calendar);
		Store store = StoreUtils.getStore(true);
		int remainSmsAmount = store.getSms_remain_amount();
		boolean flag = false;
		boolean systemFlag = false;
		int index = 0; 
		if (ids != null) {
			for (String id : ids) {
				if (!flag || !systemFlag) {
					Long customerLongId = null;
					try {
						customerLongId = Long.parseLong(id);
					} catch (Exception e) {
					}
					String msg = storeGroupToCustomer.getMsgContent();
					//验证短信剩余条数是否足够
					systemFlag = storeGroupToCustomerQueueGenerate.volidate();
					int smsNum = storeGroupToCustomerQueueGenerate.getSmsNum(msg.length());
					if (remainSmsAmount < smsNum) {
						flag = true;
						break;
					}
					remainSmsAmount -= smsNum;
					if (isEmployee != null) {
						//发短信给店长
						storeGroupToCustomerQueueGenerate.load(store, store.getBossMobile(), null, msg);
						storeGroupToCustomerQueueGenerate.generate();
						isEmployee = null;
						index = index + smsNum;
					}
					if (customerLongId != null) {
						//获取客户
						Customer customer = customerService.get(customerLongId);
						//获取短信内容
						storeGroupToCustomerQueueGenerate.load(store, customer.getMobile(),customer, msg);
						storeGroupToCustomerQueueGenerate.generate();
						smsNum = storeGroupToCustomerQueueGenerate.getSmsNum(msg.length());
						index = index + smsNum;
					}
				}
			}
			store.setSms_remain_amount(remainSmsAmount);
			systemService.save(store);
			if (systemFlag) {
				addMessage(redirectAttributes, "系统剩余短信不足！无法发送短信");
			} else if (flag) {
				if (index == 0) {
					addMessage(redirectAttributes, "剩余短信不足！无法发送短信");
				} else {
					if (isSend) {
						addMessage(redirectAttributes, "剩余短信不足，" +index + "条短信发送成功！");
					} else {
						addMessage(redirectAttributes, "剩余短信不足，可成功保存" + index + "条短信，将于预定时间的发送。。。");
					}
				}
			} else {
				if (index != 0) {
					if (isSend) {
						addMessage(redirectAttributes, index + "条短信发送成功！");
					} else {
						addMessage(redirectAttributes, "保存" + index + "条短信成功，将于预定时间开始发送。。。");
					}
				}
			}
		}
		String target = request.getParameter("target");
		if ("customer".equals(target)) {
			return "redirect:"+Global.ADMIN_PATH+"/expert/customerExam/customer";
		}
		if ("customerNotActive".equals(target)) {
			return "redirect:"+Global.ADMIN_PATH+"/expert/customerExam/customerNotActive";
		}
		return "redirect:"+Global.ADMIN_PATH+"/sms/sendStoreGroupToCustomer/" + target;
	}
	
	@RequestMapping(value = "succeed")
	public String succeed(){
		return "modules/sms/sendMsgSucceed";
	}
	
	@ResponseBody
	@RequestMapping(value = "findCustomers")
	public String findCustomers(@RequestParam(required = false) Long employeeId,
			HttpServletResponse response){
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<CustomerEmployeeRelationship> cerList = customerEmployeeRelationshipService.findByEmployee(employeeId);
		List<Customer> customerList = Lists.newArrayList();
		for (CustomerEmployeeRelationship cer : cerList) {
			Customer c = cer.getCustomer();
			customerList.add(c);
		}
		for (Customer customer : customerList) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", customer.getId());
			map.put("mobile", customer.getMobile());
			map.put("name", customer.getName());
			map.put("nickName", customer.getNickname());
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
	
}
